﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Web.UI.WebControls;
using Core.Message.Entities;
using Core.ExceptionHandling;
using Core.Controls.Message;
using vHCS.HR.Business;
using Telerik.Web.UI;
using vHCS.LS.Business;
using vHCS.HR.Entities;
using Core.Common.Session;
using Core.Common.Mail;
using System.Configuration;



namespace vHCS.K2App.MdlK2
{
    public partial class HR_ApproveRotationHR_MyTask1 : Core.NTier.UserInterface.BaseFormNotPer
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    hdfsn.Value = Request.QueryString["sn"] != null ? Request.QueryString["sn"].ToString() : "";
                    hdfSharedUser.Value = Request.QueryString["SharedUser"] != null ? Request.QueryString["SharedUser"].ToString() : "";
                    if (hdfsn.Value != "")
                    {
                        try
                        {
                            K2Collection colK2 = new K2Collection();
                            hdfEmpID.Value = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "EmpID", hdfSharedUser.Value);
                            hdfWorkingrecord.Value = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "WorkingrecordID", hdfSharedUser.Value);
                            hdfHierachyid.Value = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "ToHierarchy", hdfSharedUser.Value);
                        }
                        catch (Exception ex)
                        {
                            btnSubmitBot.Enabled = false;
                            btnSubmitTop.Enabled = false;
                            //BusinessLogicCustomException ex = new BusinessLogicCustomException("12634");
                            throw ex;
                        }

                        HR_ctrEmpHeader.LoadEmpInfoByEmpId(Convert.ToInt64(hdfEmpID.Value));
                        //Lấy thông tin người phê duyệt
                        LoadWorkingRecordForApprove();

                        txtNguoipheduyet.Text = SessionManager.UserDomain;
                        //Load thông tin trợ cấp khác lên lưới
                        dtsAllowance.SelectParameters["workingnow"].DefaultValue = hdfWorkingrecord.Value;
                        dtsAllowance.SelectParameters["workingprevious"].DefaultValue = hdfWRPrevious.Value;
                        dtgTrocapkhac.DataSourceID = dtsAllowance.ID;
                        dtgTrocapkhac.DataBind();

                        hdfEmpID.Value = HR_ctrEmpHeader.EmployeeId.ToString();

                        dpkNgayky.SelectedDate = DateTime.Now;
                        cboStatus.DataBind();

                        //Load dữ liệu history
                        dtsApproveHistory.SelectParameters["Id"].DefaultValue = hdfWorkingrecord.Value;
                        dtgApprovedHistory.DataSourceID = dtsApproveHistory.ID;
                        dtgApprovedHistory.DataBind();

                        ClientScript.RegisterStartupScript(Page.GetType(), "CheckDecision", "ChangeSalary();", true);
                        ////Lấy thông tin người phê duyệt hiện tại
                        //string deptnew = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "DeptNew");
                        //string deptold=K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "DeptOld");
                        //string hrp = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "HRP");
                        //string hr = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "HR");
                        //if (string.IsNullOrEmpty(hr))
                        //    if (string.IsNullOrEmpty(hrp))
                        //        if(string.IsNullOrEmpty(deptnew))
                        //            txtNguoipheduyet.Text = deptold;
                        //        else
                        //            txtNguoipheduyet.Text = deptnew;
                        //    else
                        //        txtNguoipheduyet.Text = hrp;
                        //else
                        //    txtNguoipheduyet.Text = hr;

                        
                    }

                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        #region Load dữ liệu Working record cần phê duyệt
        /// <summary>
        /// DungN2
        /// Load dữ liệu working record cần phê duyệt
        /// </summary>
        public void LoadWorkingRecordForApprove()
        {
            try
            {
                long workingrecord = 0;
                long.TryParse(hdfWorkingrecord.Value, out workingrecord);

                if (workingrecord > 0)
                {
                    HR_WorkingRecordBL bl = new HR_WorkingRecordBL();
                    HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();


                    hdfEformID.Value = cl.SelectEform(workingrecord);

                    bl = cl.SelectByID(workingrecord);
                    if (bl.DTO != null)
                    {
                        dpkNgayhieuluc.SelectedDate = bl.FromDate;

                        LS_ChangeFormBL bl_change = new LS_ChangeFormBL();
                        LS_ChangeFormCollection cl_change = new LS_ChangeFormCollection();
                        bl_change = cl_change.SelectByID(bl.LSStatusChangeID);
                        if (bl_change.DTO != null)
                            txtHinhthucthaydoi.Text = (SessionManager.LanguageID == "VN" || string.IsNullOrEmpty(bl_change.NameEN)) ? bl_change.NameVN : bl_change.NameEN;

                        if (bl.Decision == true)
                            rbtTerminationStatus.SelectedValue = "1";
                        else
                            rbtTerminationStatus.SelectedValue = "2";

                        txtFile.Text = bl.AttachFile;

                        LS_WorkPlaceBL bl_workplace = new LS_WorkPlaceBL();
                        LS_WorkPlaceCollection cl_workplace = new LS_WorkPlaceCollection();
                        bl_workplace = cl_workplace.SelectByID(bl.LSWorkPlaceID);
                        if (bl_workplace.DTO != null)
                            txtOffice.Text = (SessionManager.LanguageID == "VN" || string.IsNullOrEmpty(bl_workplace.NameEN)) ? bl_workplace.NameVN : bl_workplace.NameEN;

                        //Load cơ cấu tổ chức
                        txtOrgChart.Text = cl.SelectOrgChartName(bl.WorkingRecordID);

                        //Load cơ cấu chuyên môn
                        txtProChart.Text = cl.SelectProJobNameFull(bl.WorkingRecordID);

                        //Load cơ cấu quản lý
                        txtMgtChart.Text = cl.SelectMgtJobNameFull(bl.WorkingRecordID);

                        //Load cấp bậc
                        LS_JobLevelBL bl_joblevel = new LS_JobLevelBL();
                        LS_JobLevelCollection cl_joblevel = new LS_JobLevelCollection();
                        bl_joblevel = cl_joblevel.SelectByID(bl.LSLevelID);
                        if (bl_joblevel.DTO != null)
                            txtLevel.Text = (SessionManager.LanguageID == "VN" || bl_joblevel.NameEN == "") ? bl_joblevel.NameVN : bl_joblevel.NameEN;

                        //Load chức vụ
                        LS_JobTitleBL bl_title = new LS_JobTitleBL();
                        LS_JobTitleCollection cl_title = new LS_JobTitleCollection();
                        bl_title = cl_title.SelectByID(bl.JobTitleID);
                        if (bl_title.DTO != null)
                            txtJobTitle.Text = (SessionManager.LanguageID == "VN" || bl_title.NameEN == "") ? bl_title.NameVN : bl_title.NameEN;

                        //Load jobrole
                        txtJobRole.Text = cl.SelectJobRoleName(bl.WorkingRecordID);

                        //Load loại nhân viên
                        LS_EmpTypeBL bl_emptype = new LS_EmpTypeBL();
                        LS_EmpTypeCollection cl_emptype = new LS_EmpTypeCollection();
                        bl_emptype = cl_emptype.SelectByID(bl.LSEmpTypeID);
                        if (bl_emptype.DTO != null)
                            txtEmpType.Text = (SessionManager.LanguageID == "VN" || bl_emptype.NameEN == "") ? bl_emptype.NameVN : bl_emptype.NameEN;

                        txtLeader.Text = cl.ReturnLeader(bl.HierarchyId); 

                        HR_EmpCVCollection cl_empcv = new HR_EmpCVCollection();
                        txtReporter.Text = cl_empcv.GetDisplayNameByUser(bl.ReportingLine);

                        txtApprover.Text = bl.Approver;
                        txtMentor.Text = bl.Mentor;

                        chkChangeSalary.Checked = bl.IsChangeSalary;
                        chkDuytriquyenhan.Checked = bl.IsRemainRight;

                        txtGross_Now.Value = bl.GrossSalary;
                        txtLuongcanban_Now.Value = bl.BasisSalary;
                        txtKPI_Now.Value = bl.KPI;
                        txtTrocaptonghop_Now.Value = bl.GeneralSusidies;
                        txtLuongCTV_Now.Value = bl.CollaborationSalary;
                        txtGhichu.Text = bl.Note;

                        LoadWRPreviuos();
                    }
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }

        /// <summary>
        /// DungN2
        /// Load thông tin WR kế trước của nhân viên
        /// </summary>
        public void LoadWRPreviuos()
        {
            try
            {
                HR_WorkingRecordBL bl = new HR_WorkingRecordBL();
                HR_WorkingRecordCollection cl = new HR_WorkingRecordCollection();
                bl = cl.SelectPrevious(HR_ctrEmpHeader.EmployeeId, Convert.ToDateTime(dpkNgayhieuluc.SelectedDate), true, 0);
                if (bl.DTO != null)
                {
                    hdfWRPrevious.Value = bl.WorkingRecordID.ToString();

                    LS_WorkPlaceBL bl_workplace = new LS_WorkPlaceBL();
                    LS_WorkPlaceCollection cl_workplace = new LS_WorkPlaceCollection();
                    bl_workplace = cl_workplace.SelectByID(bl.LSWorkPlaceID);
                    if (bl_workplace.DTO != null)
                        txtOfficeOld.Text = (SessionManager.LanguageID == "VN" || string.IsNullOrEmpty(bl_workplace.NameEN)) ? bl_workplace.NameVN : bl_workplace.NameEN;

                    //Load cơ cấu tổ chức
                    txtOrgChartOld.Text = cl.SelectOrgChartName(bl.WorkingRecordID);

                    //Load cơ cấu chuyên môn
                    txtProChartOld.Text = cl.SelectProJobNameFull(bl.WorkingRecordID);

                    //Load cơ cấu quản lý
                    txtMgtChartOld.Text = cl.SelectMgtJobNameFull(bl.WorkingRecordID);

                    //Load cấp bậc
                    LS_JobLevelBL bl_joblevel = new LS_JobLevelBL();
                    LS_JobLevelCollection cl_joblevel = new LS_JobLevelCollection();
                    bl_joblevel = cl_joblevel.SelectByID(bl.LSLevelID);
                    if (bl_joblevel.DTO != null)
                        txtLevelOld.Text = (SessionManager.LanguageID == "VN" || bl_joblevel.NameEN == "") ? bl_joblevel.NameVN : bl_joblevel.NameEN;

                    //Load chức vụ
                    LS_JobTitleBL bl_title = new LS_JobTitleBL();
                    LS_JobTitleCollection cl_title = new LS_JobTitleCollection();
                    bl_title = cl_title.SelectByID(bl.JobTitleID);
                    if (bl_title.DTO != null)
                        txtJobTitleOld.Text = (SessionManager.LanguageID == "VN" || bl_title.NameEN == "") ? bl_title.NameVN : bl_title.NameEN;

                    //Load jobrole
                    txtJobRoleOld.Text = cl.SelectJobRoleName(bl.WorkingRecordID);

                    //Load loại nhân viên
                    LS_EmpTypeBL bl_emptype = new LS_EmpTypeBL();
                    LS_EmpTypeCollection cl_emptype = new LS_EmpTypeCollection();
                    bl_emptype = cl_emptype.SelectByID(bl.LSEmpTypeID);
                    if (bl_emptype.DTO != null)
                        txtEmpTypeOld.Text = (SessionManager.LanguageID == "VN" || bl_emptype.NameEN == "") ? bl_emptype.NameVN : bl_emptype.NameEN;

                    txtLeaderOld.Text = cl.ReturnLeader(bl.HierarchyId);

                    HR_EmpCVCollection cl_empcv = new HR_EmpCVCollection();
                    txtReporterOld.Text = cl_empcv.GetDisplayNameByUser(bl.ReportingLine);

                    txtApproverOld.Text = bl.Approver;
                    txtMentorOld.Text = bl.Mentor;

                    txtGross.Value = bl.GrossSalary;
                    txtLuongcanban.Value = bl.BasisSalary;
                    txtKPI.Value = bl.KPI;
                    txtTrocaptonghop.Value = bl.GeneralSusidies;
                    txtLuongCTV.Value = bl.CollaborationSalary;
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
        #endregion

        protected void HR_ctrEmpHeader_OnUserChanged(object sender, EventArgs e)
        {
            try
            {
                if (HR_ctrEmpHeader.EmployeeId > 0)
                {
                    LoadWorkingRecordForApprove();

                    dtsAllowance.SelectParameters["workingnow"].DefaultValue = hdfWorkingrecord.Value;
                    dtsAllowance.SelectParameters["workingprevious"].DefaultValue = hdfWRPrevious.Value;
                    dtgTrocapkhac.DataSourceID = dtsAllowance.ID;
                    dtgTrocapkhac.DataBind();

                    hdfEmpID.Value = HR_ctrEmpHeader.EmployeeId.ToString();
                }
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }

        }

        protected void btnSubmitTop_Click(object sender, EventArgs e)
        {
            try
            {
                K2Collection colK2 = new K2Collection();
                vHCS.SYS.Business.SYS_UsersBL bl_user = new vHCS.SYS.Business.SYS_UsersBL();
                vHCS.SYS.Business.SYS_UsersCollection cl_user = new vHCS.SYS.Business.SYS_UsersCollection();
                int processInstance = K2CoreLib.K2Utils.GetWorklistItem(hdfsn.Value, hdfSharedUser.Value).ProcessInstance.ID;

                //Kiểm tra hiện tại đang được phê duyệt đến cấp độ nào
                string deptnew = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "DeptNew", hdfSharedUser.Value);
                string deptold = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "DeptOld", hdfSharedUser.Value);
                string hrp = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "HRP", hdfSharedUser.Value);
                string hr = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "HR", hdfSharedUser.Value);
                List<string> NextApprover = new List<string>();
                string mailapprover = "";
                string approver="";
                Int64 role = 0;

                #region Kiểm tra cấp phê duyệt hiện tại đang đến cấp nào để gán vào datafield
                //Nếu datafield DeptNew ="" thì gán cấp phê duyệt deptnew
                if (string.IsNullOrEmpty(deptnew))
                {
                    string tohierarchy = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "ToHierarchy", hdfSharedUser.Value);
                    approver = colK2.GetLeaderOfHierarchy(Convert.ToInt64(string.IsNullOrEmpty(tohierarchy) ? "0" : tohierarchy));
                    //Lấy email người duyệt 
                    bl_user = cl_user.FindById_BL(approver);
                    if (bl_user.DTO != null)
                        mailapprover = bl_user.Email;
                    //Gán giá trị Datafield vào list
                    NextApprover.Add("DeptNew");
                    NextApprover.Add(approver);
                    NextApprover.Add("MailDeptNew");
                    NextApprover.Add(mailapprover);
                    //Nếu DeptOld=DeptNew thì bỏ qua bước phê duyệt DeptNew và tới HRP phê duyệt
                    if (deptold.Equals(approver))
                    {
                        NextApprover.Add("HRP");
                        NextApprover.Add(colK2.GetUserOfHRPLeader(HR_ctrEmpHeader.EmployeeId));
                    }
                    role = 1;
                }
                else
                {
                    //Nếu Datafield HRP ="" thì gán giá trị đatafield HRP vào -> người phê duyệt kế tiếp là HRP
                    if (string.IsNullOrEmpty(hrp))
                    {
                        approver = colK2.GetUserOfHRPLeader(HR_ctrEmpHeader.EmployeeId);
                        bl_user = cl_user.FindById_BL(approver);
                        if (bl_user.DTO != null)
                            mailapprover = bl_user.Email;
                        //Gán giá trị datafield HRP
                        NextApprover.Add("HRP");
                        NextApprover.Add(approver);
                        NextApprover.Add("MailHRP");
                        NextApprover.Add(mailapprover);
                        role = 1;
                    }
                    else
                    {
                        //Nếu Datafield HR ="" thì gán giá trị đatafield HR vào -> người phê duyệt kế tiếp là HR
                        if (string.IsNullOrEmpty(hr))
                        {
                            approver = colK2.GetUserOfHR();
                            bl_user = cl_user.FindById_BL(approver);
                            if (bl_user.DTO != null)
                                mailapprover = bl_user.Email;

                            //Gán giá trị datafield HR
                            NextApprover.Add("HR");
                            NextApprover.Add(approver);
                            NextApprover.Add("MailHR");
                            NextApprover.Add(mailapprover);
                            role = 11;
                        }
                        else
                        {
                            role = 13;
                        }
                    }
                }

                #endregion

                #region Xử lý gửi mail khi approver approve/reject
                //Lấy nội dung mail gửi trạng thái phê duyệt
                vHCS.SYS.Business.SYS_MailTemplateCollection cl_mail = new SYS.Business.SYS_MailTemplateCollection();
                SYS.Entities.SYS_MailTemplateDTO dto_mail = new SYS.Entities.SYS_MailTemplateDTO();
                dto_mail = cl_mail.GetMailContentWithSignature("WR_Approve","K2-Signature");
                string MailContent_Approve = dto_mail.ContentVN;
                string MailSubject_Approve = dto_mail.TitleVN;
                string emailapprove = "";

                string requester = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "Requester", hdfSharedUser.Value);
                string mailrequest = K2CoreLib.K2Utils.GetDataField(hdfsn.Value, "Requester", hdfSharedUser.Value);

                MailContent_Approve = MailContent_Approve.Replace("$Creator$", requester);
                MailContent_Approve = MailContent_Approve.Replace("$Status$", cboStatus.SelectedValue);
                MailContent_Approve = MailContent_Approve.Replace("$Approver$", SessionManager.UserDomain);
                MailContent_Approve = MailContent_Approve.Replace("$url$", ConfigurationManager.AppSettings.Get("LinkStaffMovement") + hdfWorkingrecord.Value);

                MailSubject_Approve = MailSubject_Approve.Replace("$Status$", cboStatus.SelectedValue);
                MailSubject_Approve = MailSubject_Approve.Replace("$Creator$", requester);

                //Lấy email người approve
                emailapprove = cl_mail.ReturnEmail(SessionManager.UserDomain);

                if (!string.IsNullOrEmpty(emailapprove))
                {
                    NextApprover.Add("MailApprover");
                    NextApprover.Add(emailapprove);
                    NextApprover.Add("MailApprover_Subject");
                    NextApprover.Add(MailSubject_Approve);
                    NextApprover.Add("MailApprover_Content");
                    NextApprover.Add(MailContent_Approve);
                }

                #endregion

                #region Xử lý gửi mail các đối tượng đặc biệt khi HR admin phê duyệt
                
                string Email = "";
                string User = ConfigurationManager.AppSettings.Get("WR_SendMail");
                string[] lstUser = User.Split(',');
                foreach (string username in lstUser)
                {
                    if (!string.IsNullOrEmpty(username))
                    {
                        Email = Email + ";" + cl_mail.ReturnEmail(username);
                    }
                }

                NextApprover.Add("MailOther");
                NextApprover.Add(Email.Trim(';'));
                #endregion

                K2CoreLib.K2Utils.ActionExecute(hdfsn.Value, cboStatus.SelectedValue, hdfSharedUser.Value, NextApprover.ToArray());
                btnSubmitBot.Enabled = false;
                btnSubmitTop.Enabled = false;

                //Insert History Comment 
                K2CoreLib.K2Utils.InsertHistoryComment(hdfEformID.Value, SessionManager.UserDomain);

                HR_WorkingRecordCollection cl_wr = new HR_WorkingRecordCollection();
                string Hisstatus = "Approved";

                //Nếu process hoàn tất
                if ((cboStatus.SelectedValue == "Approve" && !string.IsNullOrEmpty(hr)))
                {
                    cl_wr.UpdateStatusApprove(Convert.ToInt64(hdfWorkingrecord.Value));
                }
                //Nếu process bị từ chối bởi người approve
                if (cboStatus.SelectedValue.Equals("Reject"))
                {
                    Hisstatus = "Rejected";
                    cl_wr.UpdateStatusReject(Convert.ToInt64(hdfWorkingrecord.Value));
                }

                //Lưu history
                cl_wr.InsertHistory(Convert.ToInt64(hdfWorkingrecord.Value), DateTime.Now, txtNguoipheduyet.Text.Trim(), "Approver Step", Hisstatus, txtGhichu_approve.Text.Trim(), 1, role);
                ClientScript.RegisterStartupScript(Page.GetType(), "ClosePage", "ClosePage();", true);
                MessageBox.ShowByMessCode("12311");
            }
            catch (Exception ex)
            {
                AlertMessage message = UserInterfaceExceptionHandler.HandleExcetion(ex);
                MessageBox.Show(message);
            }
        }
    }
}